package com.cssiot.weixin.basic.task;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cssiot.weixin.basic.data.AccessToken;
import com.cssiot.weixin.basic.data.ErrorEntity;
import com.cssiot.weixin.basic.data.WeixinContext;
import com.cssiot.weixin.basic.data.WeixinFinalValue;

@Component("refreshAccessTokenTask")
public class RefreshAccessTokenTask {
	public static final String at = "PO6lirkDxV4t2NFCT_NBpXVe2xpwIux9RrNbctYf9Q1hfcQqG2Xgms5Ur2Lds1ZPQhbQj974UCjQ3smBR2yZ1ZEZvCO-EvXw2PXAGMwGbYZs4Ckr3Pz5fjckAwjT2MgKDCNiABAVUF";
	public void refreshToken() {
		WeixinContext.setAccessToken(at);
//		System.out.println("请求前access_token:"+WeixinContext.getAccessToken());
		HttpGet get = null;
		CloseableHttpResponse resp = null;
		CloseableHttpClient client = null;
		try {
			client = HttpClients.createDefault();
			String url = WeixinFinalValue.ACCESS_TOKEN_URL;
			url = url.replaceAll("APPID", WeixinFinalValue.APPID);
			url = url.replaceAll("APPSECRET", WeixinFinalValue.APPSECRET);
			get = new HttpGet(url);
			resp = client.execute(get);
			int statusCode = resp.getStatusLine().getStatusCode();
			if(statusCode>=200&&statusCode<300) {
				HttpEntity entity = resp.getEntity();
				String content = EntityUtils.toString(entity);
				try {
					AccessToken at = JSON.parseObject(content, AccessToken.class);
					WeixinContext.setAccessToken(at.getAccess_token());
				} catch (Exception e) {
					ErrorEntity err = JSON.parseObject(content, ErrorEntity.class);
					System.out.println("获取token异常:"+err.getErrcode()+","+err.getErrmsg());
					refreshToken();
				}
				System.out.println("最后获取的access_token:"+WeixinContext.getAccessToken());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(resp!=null) resp.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(client!=null) client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
